<!--
 * @Author: zhangyang
 * @Date: 2022-03-14 10:19:27
 * @LastEditTime: 2022-03-14 15:28:50
 * @Description: 管理员列表
-->
<script lang="ts" setup>
import useFormMode from '@/hooks/useFormMode';
import { NButton, NSpace, NSwitch } from 'naive-ui';
import type { TableDataItem, TableHeadItemPro } from '@/typings/table';
import type { AdminUser, BaseQuery, Role } from '@/typings/type';
import { addAdminUserInfo, editAdminUserInfo, getAdminList } from '@/api/system';
import dayjs from 'dayjs';

const FORM_TEMP: AdminUser = {
  autoid: 0,
  account: '',
  real_name: '',
  tel: '',
  role: '',
  is_enable: 1,
  password: ''
};

const changeStatus = async (row: AdminUser) => {
  row.is_enable = row.is_enable ? 0 : 1;
  await editAdminUserInfo(row);
  window.$message.success('修改成功！');
  getList();
};
const roleArr = ref<number[]>([]);
const changeForm = () => form.value.role = roleArr.value.join(',');

const {
  isAdd,
  isEdit,
  edit,
  sure,
  clear,
  form
} = useFormMode<AdminUser>(FORM_TEMP, {
  addCbk: async () => {
    changeForm();
    await addAdminUserInfo(form.value);
    window.$message.success('新建成功！');
  },
  modCbk: async () => {
    changeForm();
    await editAdminUserInfo(form.value);
    window.$message.success('修改成功！');
  },
  cgEffect: () => getList(),
  cpEffect: (row) => {
    roleArr.value = row.role.split(',').map((it) => +it);
  },
  extraClear: () => roleArr.value = []
});

const renderOperate = (row: TableDataItem<AdminUser>) => {
  return h(NSpace, {}, {
    default: () => [
      h(
        NButton,
        { type: 'info', size: 'small', ghost: true, onClick: () => edit(row) },
        { default: () => '编辑' }
      ),
      h(
        NButton,
        { type: row.is_enable ? 'error' : 'success', size: 'small', ghost: true, onClick: () => changeStatus(row) },
        { default: () => row.is_enable ? '禁用' : '启用' }
      ),
    ]
  })
};

const renderRole = (row: TableDataItem<AdminUser>) => {
  return h(NSpace, { vertical: true }, {
    default: () => row.role.split(',').map((item) => {
      return h('div', roleList.value.find((it) => it.autoid === +item)?.role_name ?? '非法角色')
    })
  });
};

const renderLast = (row: TableDataItem<AdminUser>) => {
  return h(NSpace, { vertical: true }, {
    default: () => [
      h('div', `最后登录时间：${dayjs(Number(row.last_time) * 1000).format('YYYY-MM-DD hh:mm:ss')}`),
      h('div', `最后登录IP：${row.last_ip}`)
    ]
  });
};

interface Query extends BaseQuery {
  real_name: string;
  tel: string;
  account: string;
};
const query = reactive<Query>({
  page: 1,
  limit: 10,
  total: 0,
  real_name: '',
  tel: '',
  account: ''
});
const roleList = ref<Role[]>([]);

const tableHead: TableHeadItemPro<AdminUser>[] = [
  { key: 'account', title: '账号' },
  { key: 'tel', title: '手机号' },
  { key: 'role', title: '角色', render: renderRole },
  { key: 'last_ip', title: '最后访问', render: renderLast, width: '320' },
  { key: 'is_enable', title: '禁用/启用', render: (row) => h(NSwitch, { value: !!row.is_enable, disabled: true }), width: '120' },
  { key: 'autoid', title: '操作', render: renderOperate, width: '180' }
];
const tableData = ref<TableDataItem<AdminUser>[]>([]);
const getList = async () => {
  const { list, role_list, total } = await getAdminList(query);
  
  tableData.value = deepClone(list);
  roleList.value = deepClone(role_list);
  query.total = total;
};

getList();
</script>

<route lang="yaml">
meta:
  title: 管理员列表
  authPath: 10000/12
</route>

<template>
  <div class="m-2">
    <NSpace>
      <NInput v-model:value="query.real_name" placeholder="请输入姓名" />
      <NInput v-model:value="query.tel" placeholder="请输入手机号" />
      <NInput v-model:value="query.account" placeholder="请输入账号" />
      <NButton type="info" ghost @click="getList">查询</NButton>
      <NButton type="success" ghost @click="isAdd=true">添加</NButton>
    </NSpace>
  </div>
  <div class="m-2">
    <YoungTablePro
      :table-data="tableData"
      :table-head="tableHead"
      :max-height="660"
      v-model:page="query.page"
      v-model:limit="query.limit"
      :total="query.total"
      @page-change="getList"
    />
  </div>
  <YoungDialog
    :is-add="isAdd"
    :is-edit="isEdit"
    @sure="sure"
    @clear="clear"
  >
    <template #body>
      <NForm :model="form" label-placement="left">
        <NFormItem label="账 号">
          <NInput v-model:value="form.account" placeholder="请输入登录账号" />
        </NFormItem>
        <NFormItem label="密 码">
          <NInput
            v-model:value="form.password"
            placeholder="请输入密码"
            tabindex="2"
            auto-complete="on"
            clearable
            type="password"
            show-password-on="click"
          />
        </NFormItem>
        <NFormItem label="手机号">
          <NInput v-model:value="form.tel" placeholder="请输入手机号" maxlength="11" />
        </NFormItem>
        <NFormItem label="姓 名">
          <NInput v-model:value="form.real_name" placeholder="请输入姓名" />
        </NFormItem>
        <NFormItem label="角 色">
          <NCheckboxGroup v-model:value="roleArr">
            <NSpace item-style="display: flex;" align="center">
              <NCheckbox
                v-for="(item, index) in roleList"
                :key="index + 'dawe'"
                :value="item.autoid"
                :label="item.role_name"
              />
            </NSpace>
          </NCheckboxGroup>
        </NFormItem>
      </NForm>
    </template>
  </YoungDialog>
</template>